package br.com.future.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import br.com.future.dao.interfaces.TipoCausaDAOI;
import br.com.future.jdbc.ConnectionFactory;
import br.com.future.log4j.Log4j;
import br.com.future.model.TipoCausa;

public class TipoCausaDAO implements TipoCausaDAOI {
	
	//chamando o metodo da classe Log4j.
	static Logger logger = Logger.getLogger(Log4j.class);
	
	private Connection conn = null;
	private boolean flag = true;

	public TipoCausaDAO(Connection conn){
		this.conn  = conn;
	}
	public TipoCausaDAO(){
		
	}
	
	@Override
	public List<TipoCausa> consultar(){
		
		verificarInstanciaDeConnection();
		
		PreparedStatement pstm = null;
		ResultSet rs = null;
		List<TipoCausa> tiposCausas = new ArrayList<TipoCausa>();
		try {
			String sql = "SELECT CD_CAUSA, DS_CAUSA FROM AM_TIPO_CAUSA";
			pstm = conn.prepareStatement(sql);
			rs = pstm.executeQuery(sql);			
			
			while(rs.next()){
				TipoCausa tipoCausa = new TipoCausa();
				tipoCausa.setCodigo(rs.getInt("CD_CAUSA"));
				tipoCausa.setDescricaoCausa(rs.getString("DS_CAUSA"));
				tiposCausas.add(tipoCausa);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			//chamando a mensagem.
			logger.error(e.getMessage());
		}finally{
			if (flag) {
				ConnectionFactory.closeConnectionOracle(conn, rs, pstm);
			}
		}
		return tiposCausas;
	}
	
	@Override
	public TipoCausa consultar(int idTipoCausa){
			
			verificarInstanciaDeConnection();
		
		    String sql = "SELECT CD_CAUSA, DS_CAUSA FROM AM_TIPO_CAUSA WHERE CD_CAUSA = ?";
		    
			PreparedStatement ps = null;
			
			ResultSet rs = null;
			
			TipoCausa tipoCausa = new TipoCausa();
			
			try{
				
				ps = conn.prepareStatement(sql);
				ps.setInt(1, idTipoCausa);
				rs = ps.executeQuery();
				
				if(rs.next()){
					tipoCausa.setCodigo(rs.getInt("CD_CAUSA"));
					tipoCausa.setDescricaoCausa(rs.getString("DS_CAUSA"));
					}
				
			}catch(SQLException e){
				e.printStackTrace();
				//chamando a mensagem.
				logger.error(e.getMessage());
			}finally{
				if (flag) {
					ConnectionFactory.closeConnectionOracle(conn, rs, ps);
				}
			}
		
			return tipoCausa;
		}

	private void verificarInstanciaDeConnection() {
		flag = true;
	
		if (conn == null) {
			conn = ConnectionFactory.getConnection();
		} else {
			flag = false;
		}
	}
}
